<!--
//
// Trigger.vue
// vue3-element-admin
//
// Created by 区区电脑 on 2023/04/11.
//
-->
<template>
    <div class="Index">
        <!-- 筛选区 -->
        <table-search-bar :config="requestBodyConfig" :model="requestBody" title="用户管理" @search="searchClicked" />

<!--        <l-r-layout :left-width="250" :min="200" :style="{height: containerHeight - 131 + 'px'}" class="lrlayout">-->
<!--            <template #left>-->
<!--                <div :style="{height: containerHeight - 133 + 'px'}" class="left-container">-->
<!--                    <div class="org-title"><span>组织部门</span>-->
<!--                        <el-checkbox v-model="hasChildren">包含子组织</el-checkbox>-->
<!--                    </div>-->
<!--                    <el-tree :data="state.orgTree" :expand-on-click-node="false" :props="{label: 'name', children: 'children'}" highlight-current @node-click="onOrgSelected" />-->
<!--                </div>-->
<!--            </template>-->
<!--            <template #right>-->
                <!-- 内容 -->
                <div class="right-container">
                    <!-- 功能按钮 -->
                    <div class="table-buttons">
                        <el-button v-permission="permission.add" type="primary" @click="addData">
                            <b-icon name="bi-plus" size="20" />
                            添加
                        </el-button>
<!--                        <el-button v-permission="permission.import" type="warning" @click="onImportData">-->
<!--                            <b-icon name="bi-cloud-upload" size="16" style="margin-right: 4px" />-->
<!--                            导入-->
<!--                        </el-button>-->
<!--                        <el-button v-permission="permission.delete" type="danger" @click="deleteDataList">-->
<!--                            <b-icon name="bi bi-trash3" size="16" style="margin-right: 4px" />-->
<!--                            删除-->
<!--                        </el-button>-->
                    </div>
                    <!--checkbox设置 :checkbox-config="{trigger: 'row', highlight: true}" -->
                    <!--radio设置 :radio-config="{trigger: 'row', highlight: true}" -->
                    <vxe-table ref="VXETable" :checkbox-config="{trigger: 'row', highlight: true}" :column-config="{ resizable: false}" :data="state.list" :height="tableHeight" :loading="state.isLoading" :row-config="{isCurrent: true, isHover: true, keyField: 'id'}"  border round show-overflow size="small" @current-change="() => {}" @radio-change="() => {}">
                        <template #empty>
                            <el-empty :image-size="100" />
                        </template>
<!--                        <vxe-column align="center" fixed="left" title="" type="checkbox" width="50" />-->
                        <vxe-column fixed="left" title="#" type="seq" width="50"/>
                        <vxe-column align="left" field="userName" :fixed="$fixedColumn('left')" title="账号" width="120"></vxe-column>
                        <vxe-column field="realName" title="姓名" width="80"></vxe-column>
                        <vxe-column align="center" field="gender" title="性别" width="70">
                            <template #default="{ row }">
                                <el-tag v-if="row.gender === 0" type="info">未知</el-tag>
                                <el-tag v-if="row.gender === 1">男</el-tag>
                                <el-tag v-if="row.gender === 2" type="danger">女</el-tag>
                            </template>
                        </vxe-column>
                        <vxe-column field="phone" title="手机号" width="120"></vxe-column>
                        <vxe-column field="email" title="邮箱" min-width="170"></vxe-column>
                        <vxe-column align="center" field="userStatus" title="状态" width="70">
                            <template #default="{ row }">
                                <el-tag v-if="row.userStatus === 0">正常</el-tag>
                                <el-tag v-if="row.userStatus === 1" type="info">停用</el-tag>
                                <el-tag v-if="row.userStatus === 2" type="danger">删除</el-tag>
                            </template>
                        </vxe-column>

<!--                        <vxe-column align="center" field="isAdmin" title="管理员" width="70">-->
<!--                            <template #default="{ row }">-->
<!--                                <el-tag v-if="row.isAdmin === 0" type="info">否</el-tag>-->
<!--                                <el-tag v-if="row.isAdmin === 1">是</el-tag>-->
<!--                            </template>-->
<!--                        </vxe-column>-->
<!--                        <vxe-column field="createdTime" min-width="180" title="创建时间">-->
<!--                            <template #default="{ row }">-->
<!--                                <span>{{ filters.dateFilter(row.createdTime) }}</span>-->
<!--                            </template>-->
<!--                        </vxe-column>-->
                        <vxe-column :resizable="false" field="action" fixed="right" title="操作" :width="$widthColumn(150)">
                            <template #default="{row}">
                                <table-action :actions="[
                                    {title: '修改', permission: permission.edit, type: 'primary', ok: editData},
                                    {title: '删除', permission: permission.delete, type: 'danger', ok: deleteData, confirm: '您确定要删除当前数据么?'},
                                    {title: '重置密码', permission: permission.add, type: 'primary', ok: resetPwdData, inMore: true},
                                ]" :data="row" />
                            </template>
                        </vxe-column>
                    </vxe-table>
                    <div class="page-config">
                        <vxe-pager v-model:current-page="requestParams.pageIndex" v-model:page-size="requestParams.pageSize" :layouts="['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']" :page-sizes="pageConfig.sizes" :total="pageConfig.total" background size="mini" @page-change="onPageChange" />
                    </div>
                </div>
<!--            </template>-->
<!--        </l-r-layout>-->
    </div>
    <EditForm ref="editForm" />
    <ResetPassword ref="resetPassword" />
    <ImportData ref="importData" />
</template>

<script setup>
import {ref, reactive, computed, onMounted, inject} from "vue";
import {useStore} from "vuex";
import {useRouter} from "vue-router";
import * as api from "./api.js"
import EditForm from "./EditForm.vue"
import ResetPassword from "./ResetPassword.vue"
import ImportData from "./ImportData.vue"

// 框架容器的高度
const containerHeight = computed(() => store.getters.containerHeight)
const {$message, $fixedColumn, $widthColumn} = window;

const props = defineProps({});
const emits = defineEmits();
const tableHeight = computed(() => store.getters.layoutType === "mobile" ? "" : containerHeight.value - 234)

// 路由
const router = useRouter();
// store
const store = useStore();
// 响应式数据
const state = reactive({
    // 表格数据加载中
    isLoading: false,
    // 表格数据
    list: [],
    // 组织数据
    orgTree: []
})

// 当前页面功能权限
const permission = {
    add: "SysUser:AddUserInfo",
    edit: "SysUser:UpdateUserInfo",
    delete: "SysUser:DeleteUserInfoByFake",
    resetPwd: "SysUser:ResetUserPassword",
    import: "SysUser:ImportUserList",
};


// 过滤器
const filters = computed(() => {
    return {
        dateFilter(val) {
            if (!val) return ""
            return $dayjs(val).format("YYYY-MM-DD HH:mm:ss")
        }
    }
})

// 请求query参数
const requestParams = reactive({
    orderCol: "id",
    isDesc: false,
    pageIndex: 1,
    pageSize: 20,
});
// 请求body参数
const requestBody = reactive({
    userName: null,
    realName: null,
    phone: null,
    email: null,
})

const otherBody = reactive({
    sysOrgIds: []
})

// 筛选区域配置
const requestBodyConfig = reactive({
    userName: {label: "账号", component: "el-input"},
    realName: {label: "姓名", component: "el-input"},
    phone: {label: "手机号", component: "el-input", inMore: true},
    email: {label: "邮箱", component: "el-input", inMore: true},
})
// 分页配置
const pageConfig = reactive({
    total: 0,
    sizes: [10, 20, 50, 100, 200]
})


// 表单
const editForm = ref();

// 添加
function addData() {
    // console.log(editForm)
    editForm.value.show({
        title: "添加",
        options: {sysOrgId: requestBody.sysOrgId},
        ok: () => {
            reload();
        }
    })
}

// 导入
const importData = ref()

function onImportData() {
    // console.log(editForm)
    //if (!requestBody.classId) return $message.error("请选择左侧试题分类")
    importData.value.show({
        title: "导入",
        options: {},
        ok: () => {
            reload();
        }
    })
}

// 删除
async function deleteData({id}) {
    console.log("删除: ", id)
    const {success, data} = await api.DeleteUserInfoByFake({id});
    if (!success) return 0;
    reload();
    $message.success("删除成功")
}

function onTableCheckboxChange(a) {
    console.log('a', a)
}

// 批量删除
const VXETable = ref();

function deleteDataList() {
    const selectedUserList = VXETable.value.getCheckboxRecords();
    if (selectedUserList.length === 0) return $message.warning("请选择用户")
    const ids = selectedUserList.map(item => item.id);
    console.log("批量删除: ", ids)
    $confirm("批量删除", "您确定要删除选中的数据么？", async (ok) => {
        if (ok) {
            const {success, data} = await api.DeleteUserList(ids);
            if (!success) return 0;
            reload();
            $message.success("删除成功")
        }
    })
}

// 修改
function editData(row) {
    editForm.value.show({
        title: "修改",
        options: {...row},
        ok: () => {
            reload();
        }
    })
}

// 点击搜索
function searchClicked() {
    console.log("搜索条件: ", requestBody)
    reload(true);
}

// 查询列表
async function loadList() {
    const params = {
        ...requestParams
    };
    const body = {
        ...requestBody,
        ...otherBody
    };
    if (body.sysOrgIds?.length === 0) {
        body.sysOrgIds = null
    }
    state.isLoading = true;
    const {success, data} = await api.GetUserPageList(params, body);
    state.isLoading = false;
    if (!success) return 0;
    const {items, totalCount} = data;
    state.list = items;
    pageConfig.total = totalCount;
}

// 重置密码
const resetPassword = ref();

// 重置密码
function resetPwdData(row) {
    resetPassword.value.show({
        title: "重置密码",
        options: {...row},
        ok: () => {
            reload();
        }
    })
}

// 分页事件
function onPageChange({type}) {
    if (type === "current") {
        loadList()
    }
    if (type === "size") {
        reload(true)
    }
}

// 刷新
function reload(resetPageIndex) {
    if (resetPageIndex) requestParams.pageIndex = 1;
    loadList()
}

// 查询组织数据
async function loadOrgTree() {
    const {success, data} = await api.GetOrgTreeList();
    if (success) {
        data.unshift({name: "全部", id: null})
        state.orgTree = data;
    }
}

// 选中了分类
const hasChildren = ref(true);

function getAllTreeId(item) {
    let ids = [item.id];
    if (item.children && item.children.length > 0) {
        for (let i = 0; i < item.children.length; i++) {
            ids = ids.concat(getAllTreeId(item.children[i]))
        }
    }
    return ids;
}

// 选中了组织
function onOrgSelected(org) {
    console.primary("选中的组织", hasChildren.value, org)
    if (hasChildren.value) {
        otherBody.sysOrgIds = getAllTreeId(org)
    } else {
        otherBody.sysOrgIds = [org.id];
    }
    otherBody.sysOrgIds = otherBody.sysOrgIds.filter(id => id);
    reload(true)
}

onMounted(() => {
    loadOrgTree();
    loadList();
})
</script>

<style lang="scss" scoped>
.Index {
    margin: 10px;
    width: calc(100% - 20px);
    box-sizing: border-box;

    .lrlayout {
        width: 100%;
    }

    .left-container {
        box-sizing: border-box;
        padding: 10px;
        background: #fff;
        box-shadow: 0 0 10px -2px rgba(0, 0, 0, 0.1);
        margin-top: 10px;
        margin-right: 5px;
        overflow: auto;

        .org-title {
            border-left: 2px solid var(--el-color-primary);
            padding: 4px 10px;
            margin-bottom: 10px;
            background: #f1f1f1;
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
        }
    }

    .right-container {
        box-sizing: border-box;
        padding: 10px;
        background: #fff;
        box-shadow: 0 0 10px -2px rgba(0, 0, 0, 0.1);
        margin-top: 10px;
        //margin-left: 5px;
    }

}
</style>
